import React, { Component, Fragment } from 'react'
import { withRouter } from 'react-router-dom'
import './top_nav.less'
import Logo from '../../assests/images/logo.png'
import TwoCode from '../../assests/images/two-code.png'
import { Button, Modal, Form, Input, message, Dropdown } from 'antd'
import { MobileOutlined, LockOutlined, WeiboOutlined, WechatOutlined, MailOutlined, DownOutlined, TagsOutlined, HomeOutlined, CrownOutlined, LogoutOutlined, ExclamationCircleOutlined, ReadOutlined, FolderViewOutlined, SolutionOutlined, YoutubeOutlined } from '@ant-design/icons';
import { setToken, setMemberInfo, getMemberInfo, clearStorage } from '../../utils/auth'
import memberApi from '../../api/member'

class TopNav extends Component {
  state = {
    title: [
      { id: '111', name: '课程', path: '/course' },
      { id: '222', name: '文章', path: '/blog' },
      { id: '333', name: '导航', path: '/guide' },
      { id: '444', name: '资源', path: '/resource' },
    ],
    loginVisavle: false,
    loginType: 'password',
    visible: false,
    isSendCode: false,
    codeTime: 6
  }

  toPage = (path) => {
    return () => {
      this.props.history.replace(path)
    }
  }
  showLogin = () => {
    this.setState({
      loginVisavle: true
    })
  }
  handleCancel = () => {
    this.setState({
      loginVisavle: false
    })
  }
  // 密码登录方法
  loginPassword = (data) => {
    this.setState({
      loginType: 'password'
    })
    memberApi.loginPassword(data).then(res => {
      if (res.success) {
        setToken(res.data.token)
        memberApi.getInfoByToken().then(resp => {
          if (resp.success) {
            setMemberInfo(resp.data.data)
            message.success(res.data.message)
            this.setState({
              loginVisavle: false
            })
            window.location.reload()
          }
        })
      }
    })
  }
  // 发送验证码
  sendCode = (e) => {
    memberApi.sendEmailCode({ email: e }).then(res => {
    })
    this.setState({
      isSendCode: true
    })
    this.timer = setInterval(() => {
      let time = this.state.codeTime
      time--
      this.setState({
        codeTime: time
      })
      if (time <= 0) {
        clearInterval(this.timer);
        this.setState({
          isSendCode: false,
          codeTime: 6
        })
      }
    }, 1000)
  }
  // 验证码登录方法
  loginCode = (data) => {
    this.setState({
      loginType: 'code'
    })
    memberApi.loginCode(data).then(res => {
      if (res.success) {
        setToken(res.data.token)
        memberApi.getInfoByToken().then(resp => {
          if (resp.success) {
            setMemberInfo(resp.data.data)
            message.success(res.data.message)
            this.setState({
              loginVisavle: false
            })
            window.location.reload()
          }
        })
      }
    })
  }
  // 微信登录方法
  loginWX = () => {
    this.setState({
      loginType: 'wx'
    })
    message.warning("微信登录功能暂未开放")
  }
  // 微博登录方法
  loginWB = () => {
    this.setState({
      loginType: 'wb'
    })
    message.warning("微博登录功能暂未开放")
  }

  // 不同组件
  userPassword = () => {
    return (
      <Fragment>
        <h1 style={{ marginBottom: '20px', textAlign: 'center' }}>密码登录</h1>
        <Form
          onFinish={this.loginPassword}>
          <Form.Item
            name="phone"
            rules={[{ required: true, message: '请输入您的手机号!' }]}
          >
            <Input prefix={<MobileOutlined className="site-form-item-icon" />} placeholder="手机号" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入您的密码!' }]}
          >
            <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} placeholder="密码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}> 登录 </Button>
          </Form.Item>
          <Form.Item>
            <Button type="link" style={{ width: '100%' }} onClick={this.loginCode}> 验证码登录 </Button>
          </Form.Item>
          <Form.Item>
            <div style={{ display: 'flex', justifyContent: 'space-around' }}>
              <WechatOutlined style={{ fontSize: '30px', color: 'green', cursor: 'pointer' }} onClick={this.loginWX} />
              <WeiboOutlined style={{ fontSize: '30px', color: 'red', cursor: 'pointer' }} onClick={this.loginWB} />
            </div>
          </Form.Item>
        </Form>
      </Fragment>
    )
  }
  userCode = () => {
    const { isSendCode, codeTime } = this.state
    return (
      <Fragment>
        <h1 style={{ marginBottom: '20px', textAlign: 'center' }}>验证码登录</h1>
        <Form
          onFinish={this.loginCode}>
          <Form.Item
            name="email"
            rules={[{ required: true, message: '请输入您的邮箱!' }]}
          >
            <Input.Search
              placeholder="邮箱"
              prefix={<MailOutlined className="site-form-item-icon" />}
              enterButton={!isSendCode ? '发送验证码' : `${codeTime}s后重新发送`}
              size="large"
              disabled={isSendCode}
              onSearch={this.sendCode} />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[{ required: true, message: '请输入您的验证码!' }]}
          >
            <Input.Password prefix={<LockOutlined className="site-form-item-icon" />} placeholder="验证码" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: '100%' }}> 登录 </Button>
          </Form.Item>
          <Form.Item>
            <Button type="link" style={{ width: '100%' }} onClick={this.loginPassword}> 密码登录 </Button>
          </Form.Item>
          <Form.Item>
            <div style={{ display: 'flex', justifyContent: 'space-around' }}>
              <WechatOutlined style={{ fontSize: '30px', color: 'green', cursor: 'pointer' }} onClick={this.loginWX} />
              <WeiboOutlined style={{ fontSize: '30px', color: 'red', cursor: 'pointer' }} onClick={this.loginWB} />
            </div>
          </Form.Item>
        </Form>
      </Fragment>
    )
  }
  userWX = () => {
    return (
      <Fragment>
        <h1 style={{ marginBottom: '20px', textAlign: 'center' }}>微信登录</h1>
        <Form>
          <Form.Item>
            <div style={{ width: '100%', height: '200px', display: 'flex', justifyContent: 'center' }}>
              <img src={TwoCode} alt="二维码" style={{ width: '200px', height: '200px' }} />
            </div>
          </Form.Item>
          <Form.Item>
            <Button type="link" style={{ width: '100%' }} onClick={this.loginPassword}> 密码登录 </Button>
          </Form.Item>
        </Form>
      </Fragment>
    )
  }
  userWB = () => {
    return (
      <Fragment>
        <h1 style={{ marginBottom: '20px', textAlign: 'center' }}>微博登录</h1>
        <Form>
          <Form.Item>
            <div style={{ width: '100%', height: '200px', display: 'flex', justifyContent: 'center' }}>
              <img src={TwoCode} alt="二维码" style={{ width: '200px', height: '200px' }} />
            </div>
          </Form.Item>
          <Form.Item>
            <Button type="link" style={{ width: '100%' }} onClick={this.loginPassword}> 密码登录 </Button>
          </Form.Item>
        </Form>
      </Fragment>
    )
  }
  handleVisibleChange = flag => {
    this.setState({ visible: flag });
  };
  handleLogout = () => {
    Modal.confirm({
      title: '确定退出登录吗?',
      icon: <ExclamationCircleOutlined />,
      onOk: () => {
        clearStorage()
        this.props.history.push("/home")
      },
      onCancel: () => {
        console.log('Cancel');
      },
    });

  }
  goOwn = (active) => {
    return () => {
      this.props.history.push({
        pathname: '/own',
        search:'active='+active
      })
    }
  }
  handleSign = (e) => {
    e.preventDefault();
  }
  getMemberBox = () => {
    return (
      <div className="member-box">
        <ul>
          <li onClick={this.goOwn('concern')}>
            <p><FolderViewOutlined /></p>
            <h3>关注</h3>
          </li>
          <li onClick={this.goOwn('fans')}>
            <p><SolutionOutlined /></p>
            <h3>粉丝</h3>
          </li>
        </ul>
        <Button icon={<TagsOutlined />} type="primary" size="small" shape="round" onClick={e => this.handleSign(e)}>签到</Button>
        <ol>
          <li onClick={this.goOwn('seting')}>
            <div>
              <CrownOutlined />
              <span>设置</span>
            </div>
          </li>
          <li onClick={this.goOwn('home')}>
            <div>
              <HomeOutlined />
              <span>个人中心</span>
            </div>
          </li>

          <li onClick={this.handleLogout}>
            <div>
              <LogoutOutlined />
              <span>退出登录</span>
            </div>
          </li>

        </ol>
      </div>
    )
  }
  searchAll = (e) => {
    let key = e.trim()
    if (key) {
      this.props.history.push({
        pathname: "/search",
        search: "key="+key
      })
    }

  }
  render() {
    const { title, loginType } = this.state
    const { active } = this.props
    const memberInfo = getMemberInfo()
    return (
      <div className="top-nav-container" style={{ ...this.props.style }}>
        {/* 头部导航 */}
        <nav className="top-nav">
          <p onClick={this.toPage('/home')}><img src={Logo} alt="logo" style={{ width: '80px' }} /></p>
          {
            title.map(item => {
              return (
                <p onClick={this.toPage(item.path)} className={active === item.path ? "top-nav-item nav-active" : "top-nav-item"} key={item.path}>{item.name}</p>
              )
            })
          }
        </nav>
        <div style={{ width: '300px' }}>
          {this.props.history.location && this.props.history.location.pathname !== "/search" ?
            <Input.Search placeholder="输入关键词搜索" onSearch={this.searchAll} enterButton /> : ""
           }

        </div>

        {
          memberInfo ? <Dropdown
            trigger={['click']}
            placement="bottomRight"
            arrow
            overlay={this.getMemberBox()}
          >
            <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
              <img style={{ width: '30px', height: '30px', borderRadius: '50%', border: '1px solid #ccc', marginRight: '10px' }} src={memberInfo.avatar} alt="avatar" />
              {memberInfo.nickname} <DownOutlined />
            </a>
          </Dropdown>
            : <Button type="primary" onClick={this.showLogin}>登录</Button>
        }

        {/* 弹框 */}
        <Modal
          visible={this.state.loginVisavle}
          onCancel={this.handleCancel}
          footer={false}>
          <div className="login-box" style={{ padding: '20px 50px 0' }}>
            {
              loginType === 'password' ? this.userPassword() : loginType === 'code' ? this.userCode() : loginType === 'wx' ? this.userWX() : this.userWB()
            }
          </div>
        </Modal>
      </div>
    )
  }
}
export default withRouter(TopNav)